package tjx.Servlet;

import tjx.DbDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "login",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String errMsg = "";
        RequestDispatcher rd;
        String username = request.getParameter("username");
        String password= request.getParameter("pass");
        try {
                DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/1613580002", "root", "tjxwq42222");
                ResultSet rs = dd.query("select password from t_user " + "where username=?", username);
                if (rs.next())
                {
                    if (rs.getString("password").equals(password))
                    {
                        HttpSession session = request.getSession(true);
                        session.setAttribute("username", username);
                        rd = request.getRequestDispatcher("/form.jsp");
                        rd.forward(request, response);
                    }
                }
                else
                    {
                    errMsg += "您的用户名、密码不存在，请先注册";
                    }
            }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        if (errMsg != null && !errMsg.equals("")) {
            rd = request.getRequestDispatcher("/login.jsp");
            request.setAttribute("err", errMsg);
            rd.forward(request, response);
        }
    }
}